<?php

namespace App\Http\Controllers\Bus;

use App\Http\Controllers\Controller;
use App\Models\Bus\Bus;
use App\Models\Bus\BusScrap;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class BusScrapController extends Controller
{
    /**
     * 报废车辆信息列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function busScrapList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);
        $data = $this->getBusScrapList($params)->get()->toArray();
        if ($data) {
            $data = $this->busScrapTransData($data);
        }
        $dataCount = $this->getBusScrapList($countParams)->count();
        return response()->formatJson(['personnel' => $data, 'count' => $dataCount]);
    }

    public function getBusScrapList($params): \Illuminate\Database\Eloquent\Builder
    {
        $result = BusScrap::query()
            ->with([
                'bus' => function ($query) {
                    $query->select('brand', 'license_plate_num', 'type', 'engine_num', 'frame_nun', 'id');
                },
            ])
            ->with([
                'user' => function ($query) {
                    $query->select('username', 'name', 'phone', 'id');
                },
            ]);

        $ids = [];
        if (isset($params['license_plate_num'])) {
            $ids = Bus::query()->select('id')
                ->where('license_plate_num', 'like', '%'.$params['license_plate_num'].'%')
                ->orderBy('id')
                ->pluck('id')
                ->toArray();
            $result->whereIn('bus_id', $ids);
        }
        if (isset($params['pageNumber'], $params['pageSize'])) {
            $result
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }
        return $result;
    }

    /**
     * 数据转化
     *
     * @param  array  $data
     *
     * @return array
     */
    public function busScrapTransData(array $data): array
    {
        $model = [
            '东风牌',
            '亚星牌',
            '宇通牌',
            '中通牌',
        ];
        $type = [
            '燃气车',
            '纯电动',
        ];
        foreach ($data as $key => $item) {
            foreach ($item as $filed => $value) {
                if ($filed === 'bus' && $value != null) {
                    $data[$key]['license_plate_num'] = $value['license_plate_num'];
                    $data[$key]['engine_num'] = $value['engine_num'];
                    $data[$key]['frame_nun'] = $value['frame_nun'];
                    $data[$key]['brand'] = $model[$value['brand']];
                    $data[$key]['type'] = $type[$value['type']];
                    unset($data[$key]['bus']);
                }
                if ($filed === 'user' && $value != null) {
                    $data[$key]['username'] = $value['username'];
                    $data[$key]['name'] = $value['name'];
                    $data[$key]['phone'] = $value['phone'];
                    unset($data[$key]['user']);
                }
            }
        }

        return $data;
    }

    /**
     * 创建车辆报废信息
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function store(Request $request)
    {
        $params = $request->all();
        unset($params['license_plate_num']);
        //查询是否已有此车辆的报废信息
        $query = BusScrap::query()->select('id')
            ->where('bus_id', $params['bus_id'])
            ->count();
        if ($query) {
            return response()->formatJson('', '已有此车辆的报废信息,请核对后再处理!');
        }
        //插入新数据
        $params['user_id'] = Auth::user()->id;
        $busScrap = new BusScrap($params);
        $result = $busScrap->save();
        //更改akbus_bus中车辆状态
        if ($result) {
            $query = Bus::query()
                ->where('id', $params['bus_id'])
                ->update(['is_scrap' => 1]);
            $message = $query ? '添加成功' : '添加失败';
        } else {
            $message = '添加失败';
        }
        return response()->formatJson($result, $message);
    }

    /**
     * 获取报废车辆数据到编辑表单页面
     *
     * @param $id
     *
     * @return mixed
     */
    public function edit($id)
    {
        $busScrap = BusScrap::with('bus')->find($id)->toArray();
        if ($busScrap['bus']) {
            $busScrap['license_plate_num'] = str_replace('陕G', '', $busScrap['bus']['license_plate_num']);
            unset($busScrap['bus']);
        }
        return response()->formatJson($busScrap);
    }

    /**
     * 修改车辆报废信息
     *
     * @param  Request  $request
     * @param           $id
     *
     * @return mixed
     */
    public function update(Request $request, $id)
    {
        $params = $request->all();
        $busScrap = BusScrap::query()->find($id);
        $params['user_id'] = Auth::user()->id;
        $result = $busScrap->update([
            'scrap_time' => $params['scrap_time'], 'user_id' => $params['user_id'], 'note' => $params['note'],
        ]);
        $message = $result ? '修改成功' : '修改失败';

        return response()->formatJson($result, $message);
    }

    /**
     * 删除车辆报废信息
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function destroy(Request $request)
    {
        //开启事务
        DB::beginTransaction();
        try {
            if ($request->has('ids')) {
                $ids = explode(',', $request['ids']);
                //更新akbus_bus的车辆状态后删除报废车辆
                foreach ($ids as $v) {
                    $bus_id = DB::table('akbus_bus_scrap')->where('id', $v)->value('bus_id');
                    DB::table('akbus_bus')->where('id', $bus_id)->update(['is_scrap' => 0]);
                }
                BusScrap::destroy($ids);
                $result = true;
            }
            DB::commit();
        } catch (\Exception $e) {
            //接收异常处理并回滚
            DB::rollBack();
            $result = false;
        }
        $message = $result ? '删除成功' : '删除失败';

        return response()->formatJson($result, $message);
    }

    /**
     * 获取车牌号与对应id数组
     *
     * @return mixed
     */
    public function idLicensePlateNumList()
    {
        $result = Bus::query()->select('id', 'license_plate_num')->get();
        return response()->formatJson($result);
    }
}
